package cn.yuanqiao.archive.bianyan.utils;

import cn.yuanqiao.archive.bianyan.domain.YqZtcgFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


/**
 * @ProjectName: ruoyi-modules-system
 * @Package: cn.yuanqiao.archive.bianyan.utils
 * @ClassName: ZipUtils
 * @Author: lenovo
 * @Description: hbWang
 * @Date: 2023/7/11 17:02
 * @Version: 1.0
 */
public class ZipUtils {
    private static final Logger log = LoggerFactory.getLogger(ZipUtils.class);


    /**
     * @param downLoadUrl 文件信息
     * @param zipName     压缩包名称
     * @param response
     * @throws IOException
     */
    public void downloadFolder(List<YqZtcgFile> downLoadUrl, String zipName, HttpServletResponse response, String zipPath) throws Exception {
        if (downLoadUrl.size() > 0) {
            //压缩文件
            File file = compressedFileToZip(zipName, downLoadUrl, zipPath);
            //输出文件流
            writeFileToRes(response, file.getName(), file);
            //删除压缩包
            if (file.exists()) {
                file.delete();
            }
        }

    }


    /**
     * 压缩文件
     *
     * @param datumName    压缩包名称
     * @param filePathList 附件路径
     * @return File
     * @throws Exception Exception
     */
    private File compressedFileToZip(String datumName, List<YqZtcgFile> filePathList, String zipPath) throws Exception {
        //压缩包具体名称（拼接时间戳防止重名）
        String zipFileName = datumName + "-" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".zip";
        //生成压缩包存储地址（最后会删掉）
        String fileZip = zipPath + zipFileName;
        OutputStream os = null;
        ZipOutputStream zos = null;
        File file = new File(fileZip);
        try {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            os = new FileOutputStream(file);
            //压缩文件
            zos = new ZipOutputStream(os);
            byte[] buf = new byte[1024];
            for (YqZtcgFile filePath : filePathList) {
                File tempFile = new File(zipPath + filePath.getFilePath());
                //在压缩包中添加文件夹
                //zos.putNextEntry(new ZipEntry("测试/"+tempFile.getName()));
                //直接在压缩包中添加文件
                zos.putNextEntry(new ZipEntry(tempFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(tempFile);
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.toString());
            throw new Exception("文件打包:" + e.getMessage());
        } finally {
            //关闭流
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭流
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }


    /**
     * 输出文件流到response
     *
     * @param response response
     * @param fileName fileName
     * @param file     file
     * @throws IOException IOException
     */
    private void writeFileToRes(HttpServletResponse response, String fileName, File file) throws IOException {
        FileInputStream inputStream = new FileInputStream(file);
        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
        response.setContentType("application/octet-stream");
        //2.设置文件头：最后一个参数是设置下载文件名
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.addHeader("Content-Length", "" + file.length());

        //3.通过response获取ServletOutputStream对象(out)
        ServletOutputStream out = response.getOutputStream();

        int b = 0;
        byte[] buffer = new byte[1024];
        while (b != -1) {
            b = inputStream.read(buffer);
            //4.写到输出流(out)中
            out.write(buffer, 0, b);
        }
        out.flush();
        out.close();
        inputStream.close();

    }

}
